<?php

$error = '<div class="error">%s</div>';

if( !empty( $_POST['messages'] ))
	if( isset( $_POST['delete'] )) {
		$db->query( "DELETE FROM user_msg WHERE owner = %d AND id IN (%s)",
			$user->id, implode( ',', array_map('intval', $_POST['messages'] )));
	}

if( isset( $_POST['subject'] )) {
	// Name Validation
	if( empty( $_POST['subject'] ))
		printf( $error, 'Bitte Betreff angeben' );
	elseif( empty( $_POST['to'] ))
		printf( $error, 'Bitte Empfänger angeben' );
	elseif( empty( $_POST['content'] ))
		printf( $error, 'Bitte Nachricht angeben' );
	elseif( !$to = $db->query( "SELECT id FROM user_data WHERE name = '%s'", $_POST['to'] )->value())
		printf( $error, 'Empfänger unbekannt' );
	elseif( strlen( $_POST['content'] ) > 10000 && strlen( $_POST['subject'] ) > 32 )
		printf( $error, 'Betreff oder Nachricht zu lang' );
	elseif( $to == $user->id )
		printf( $error, 'Nachrichten mit sich selber zu schreiben, zeugt von Schizophrenie!' );
	else {
		$message = array(
			"date" => time(),
			"to" => $to,
			"from" => $userdata['id'],
			"subject" => $_POST['subject'],
			"content" => $_POST['content'] );

		$message['owner'] = $to;
		$db->insert( 'user_msg', $message );

//		$message['owner'] = $user->id;
//		$db->insert( 'user_msg', $message );

		throw new redirect(PAGE_SELF);
	}
}

if( empty( $_GET['view'] )) {
	$sql = "SELECT msg.*, von.name 'from_name', an.name 'to_name' FROM `user_msg` msg
					LEFT JOIN `user_data` von ON ( msg.`from` = von.id )
					LEFT JOIN `user_data` an ON ( msg.`to` = an.id )
					WHERE msg.owner = %d AND msg.`%s` = %d";

	$inbox = $db->query( $sql, $user->id, 'to', $user->id );
	//$inbox = $db->query( $sql, $user->id, 'from', $user->id );

	$form = new form( PAGE_SELF, 'Senden' );
	$form->text( 'to', 'Empfänger' )->input( 'class', 'input-xxlarge' );
	$form->text( 'subject', 'Betreff' )->input( 'class', 'input-xxlarge' );

	$form->textarea( 'content', 'Nachricht' )
	->input( 'class', 'input-xxlarge' )
	->input( 'rows', 10 );

	template( 'messages' )->display(array(
		'incoming' => $inbox->assocs(),
		'form' => $form
	));
} else {

}
